# -*- coding: utf-8 -*-

from odoo import models, fields, api


class WechatUser(models.Model):
    _inherit = 'wechat.user'

    checked_in_salesman = fields.Many2one(
        'exhibition.users',
        ondelete='SET NULL',
        string='首次签到销售',
        help='related salesman when first checked in',
    )
    checked_in_salesman_name = fields.Char(string='首次签到销售', related='checked_in_salesman.name')
    checked_in_department = fields.Many2one(
        'exhibition.department',
        ondelete='SET NULL',
        string='首次签到部门',
        help='related department when first checked in',
    )
    checked_in_department_name = fields.Char(string='首次签到部门', related='checked_in_department.name')

    exhibit_visit_histories = fields.One2many(
        comodel_name='exhibition.exhibit_visit_history',
        inverse_name='wechat_uid',
        string='展品访问历史',
    )

    checkin_histories = fields.One2many(
        comodel_name='exhibition.checkin',
        inverse_name='wechat_uid',
        string='签到历史',
    )

    @api.model
    def update_checked_in_department(self):
        for wechat_user in self.search([]):
            if not wechat_user.checked_in_salesman or not wechat_user.checked_in_salesman.department:
                continue
            wechat_user.sudo().write({
                'checked_in_department': wechat_user.checked_in_salesman.department.id,
            })

    def btn_exhibit_visit_history(self):
        return {
            'type': 'ir.actions.act_window',
            'name': '展品扫码访问历史',
            'res_model': 'exhibition.exhibit_visit_history',
            'view_id': self.env.ref('exhibition.view_exhibit_visit_history_tree').id,
            'view_mode': 'tree',
            'search_view_id': self.env.ref('exhibition.view_exhibit_visit_history_search').id,
            'context': {'search_default_wechat_uid': self.ids[0]},
        }

    def btn_wechat_user_checkin_history(self):
        return {
            'type': 'ir.actions.act_window',
            'name': '签到历史',
            'res_model': 'exhibition.checkin',
            'view_id': self.env.ref('exhibition.view_checkin_tree').id,
            'view_mode': 'tree',
            'search_view_id': self.env.ref('exhibition.view_checkin_search').id,
            'context': {'search_default_wechat_uid': self.ids[0]},
        }
